#!/usr/bin/env perl
use FindBin;
use lib "$FindBin::Bin/lib";
use lib "$FindBin::Bin/pllib/lib/perl5";

use strict;
use IO::File;
use Getopt::Long;
use Cwd 'abs_path';
use File::Basename;
use POSIX;

use Patcher;

Getopt::Long::Configure("pass_through");

my $homePath = abs_path("$FindBin::Bin/..");
my $progName = $FindBin::Script;
my @uname    = uname();
my $osType   = 'unix';
$osType = 'windows' if ( $uname[0] =~ /Windows/i );

sub usage {
    print("Usage:$progName --ins INSName --version VERSION\n");
    print("                --backupdir BackupSaveDir --targetdir TargetDir\n");
    exit(-1);
}

sub main {
    if ( $osType eq 'windows' ) {
        $ENV{PATH} = "$homePath/../7-Zip;$ENV{ProgramFiles}/7-Zip;" . $ENV{PATH};
    }

    my $isHelp;
    my $isVerbose = 0;
    my $insName;
    my $version;
    my $targetDir;
    my $backupDir;

    GetOptions(
        'h|help'      => \$isHelp,
        'v|verbose=i' => \$isVerbose,
        'ins=s'       => \$insName,
        'version=s'   => \$version,
        'backupdir=s' => \$backupDir,
        'targetdir=s' => \$targetDir
    );

    usage() if defined($isHelp);

    my $hasOptionError = 0;
    if ( not defined($version) or $version eq '' ) {
        $hasOptionError = 1;
        print("ERROR: Version not defined(option --version).\n");
    }

    if ( not defined($targetDir) or $targetDir eq '' ) {
        $hasOptionError = 1;
        print("ERROR: Target directory not defined(option --targetdir).\n");
    }
    elsif ( not -e $targetDir ) {
        $hasOptionError = 1;
        print("ERROR: Target directory:$targetDir not exist.\n");
    }

    if ( not defined($backupDir) or $backupDir eq '' ) {
        $hasOptionError = 1;
        print("ERROR: Backup directory not defined(option --backupdir).\n");
    }
    elsif ( not -d dirname($backupDir) ) {
        $hasOptionError = 1;
        my $backupRoot = dirname($backupDir);
        print("ERROR: Backup directory:$backupRoot not exist.\n");
    }

    if ( $hasOptionError == 1 ) {
        usage();
    }

    my $patcher = Patcher->new( $homePath, $backupDir, 5 );

    my $status = 0;
    $status = $patcher->rollback( $insName, $version );

    return $status;
}

exit main();

